<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" :visible.sync="show" class="dialog_index dialog_banner"
   :before-close="cancle">
    <el-form ref="bannerForm" v-loading="loading" class="frontMenu">
      <el-tabs type="card" v-model="activeName">
          <el-tab-pane :label="item.site"  :name="item.site" v-for="item  in formList" :key="item.id">
            <el-form-item label="父级菜单：">
              <el-select v-model="item.parent_relatetion_id" filterable clearable 
              :placeholder="'父级菜单('+item.site+')（必填项)'"  @change="(value)=>changeMenuName(value)"
              @focus="(event) => getMenuNameList(event, item)" >
                <el-option v-for="menuName in item.menuNameList" :key="menuName.relatetion_id" :value="menuName.relatetion_id" :label="menuName.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜单名称：">
              <el-input  :placeholder="'菜单名称('+item.site+')（必填项)'" v-model="item.name"></el-input>
            </el-form-item>
            <el-form-item label="图片：" class="uploadImage" v-show="item.parent_path == '/products'">
              <el-upload class="uploadIcon" :action="actionUrl" 
              :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item)"
                :on-error="handleError" :before-upload="beforeUpload"
              :show-file-list="false" accept=".png " :data="{type:'front_menu', imageheight: imgH, imagewidth: imgW}" >
                <br><el-button size="small" type="primary" @click.stop="closeDrawerDialog">图库选择</el-button> 
                <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              </el-upload>
              <el-image :src="utils.setCdnUrl() + item.image" v-show="item.image"></el-image>
              <p class="upload__tip">建议上传.png格式，且尺寸比例为1:1，大小≤1M，每次只能上传一个</p>
            </el-form-item>

            <el-form-item label="地址：">
              <el-input  :placeholder="'地址('+item.site+')（必填项)'" v-model="item.path" @change="changePath"></el-input>
            </el-form-item>
              <el-form-item label="顺序：">
              <el-input  :placeholder="'顺序('+item.site+')（必填项)'" v-model="item.weigh" @change="changeSite"></el-input>
            </el-form-item>
          </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'front_menu'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
  </el-dialog>
</template>

<script>
import { frontMenuEditGet, frontMenuEditPost, allFrontMenu } from '@/api/front/frontMenu.js'
import Drawer  from '@/components/Gallery/index.vue' 

export default {
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  data() {
    return {
      formList: [],
      menuNameList: [],
      loading: false,
      activeName: '',
      actionUrl: '/api/api/general/upload',
      showDrawer: false,
      imgH:'',
      imgW: '',
    }
  },
  watch:{
    id: function(){
      if (this.show) {
        this.loading = true
        this.getFrontMenuEdit()
      }
    }
  },
  components: { Drawer },
  methods: {
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if(data && data.filePathNameHttp )  { 
        for(let i = 0; i < this.formList.length; i++){
          this.$set(this.formList[i], 'image', data.filePathName)
        }
      }
    },
    getAllFrontMenu(){
      allFrontMenu().then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          let sitData = data[list[i].site_id]
           let array = [{
            id: 0,
            label: "无",
            relatetion_id: 0
          }]
          sitData = array.concat(sitData)
          list[i].menuNameList =sitData
        }
        this.formList = list
      })
    },
     handleSuccess(response){ //所有站点同步
      for(let i = 0; i < this.formList.length; i++){
        this.$set(this.formList[i], 'image', response.data.filePathName)
      }
      this.$message.success('上传图片成功')   
    },
    handleError(){
      this.$message.error('上传图片失败')   
    },
    beforeUpload(file){
      let that = this
      if(file.type !== 'image/png'){
        this.$message.error("仅支持.png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width ==  img.height ;
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        return file
      })
      return isSize
    },
    changeMenuName(value){
      let list = this.formList
      for(let i = 0; i < list.length; i++){
        list[i].parent_relatetion_id = value
        for(let j = 0; j < list[i].menuNameList.length; j++ ){
          let ele = list[i].menuNameList[j]
          if(ele.relatetion_id == value ){
            list[i].pid = ele.id
            list[i].parent_path = ele.path
          }
        }
      }
      this.formList = list
    },
    getFrontMenuEdit () {
      let params = {
        relatetion_id: this.id
      }
      frontMenuEditGet(params).then(res=>{
        if (res.status == 200){
          let data = res.data
          for(let i = 0;i < data.length; i++){
            data[i].menuNameList = []
          }
          this.formList = data
          if (data.length > 0){
            this.activeName = data[0].site
          }
          this.getAllFrontMenu()
        }
         this.loading = false
      })
      
    },
    changePath(value ){
      let list = this.formList
      for(let i = 0; i < list.length; i++){
        list[i].path = value
      }
    },
    changeSite(value ){
      let list = this.formList
      for(let i = 0; i < list.length; i++){
        list[i].weigh = value
      }
    },
    cancle(){
      this.$emit('closeDialog')
    },
    submitForm(){
      let status = this.validateForm()
      if (status) {
        this.editFrontMenu()
      }
    },
    validateForm (){
      let list = this.formList
      let status = true
      for(let i = 0; i < list.length; i++){
        if( list[i].pid === ''){ //父级菜单不填
          this.$message.error('站点' + list[i].site + '父级菜单为必填项')
          status = false
          break
        }
        if (list[i].name === '') {
          this.$message.error('站点' + list[i].site + '菜单名称为必填项')
          status = false
          break
        }
        if (list[i].name.length > 50) {
          this.$message.error('站点' + list[i].site + '菜单名称最多50字符')
          status = false
          break
        }
         if (list[i].parent_path == '/products' && list[i].image ==  '') {
          this.$message.error('站点' + list[i].site + '图片为必填项')
          status = false
          break
        }
         if (list[i].path === '') {
          this.$message.error('站点' + list[i].site + '地址为必填项')
          status = false
          break
        }
        if (list[i].path.length > 100) {
          this.$message.error('站点' + list[i].site + '地址最多100字符')
          status = false
          break
        }
        if (list[i].weigh === '') {
          this.$message.error('站点' + list[i].site + '顺序为必填项')
          status = false
          break
        }
        if (list[i].weigh.toString().length > 2) {
          this.$message.error('站点' + list[i].site + '顺序最多2字符')
          status = false
          break
        } 
      }
      return status
    },
    editFrontMenu(){
      let params = {
        data: JSON.stringify(this.formList),
        relatetion_id: this.id
      }
      frontMenuEditPost(params).then(res=>{
        if(res.state == 1){
          this.$message.success('菜单编辑成功')
          this.cancle() 
        }
      })
    },
  }
}
</script>

<style lang="scss">

</style>